const router = require('koa-router')()
const util = require('../utils/util')
const Leave = require('../models/leaveSchema')
const Dept = require('../models/deptSchema')

router.prefix('/leave')

// 消息数
router.get("/count", async (ctx) => {
	console.log('------------------------------------------------')
	let authorization = ctx.request.headers.authorization;
	let {
		data
	} = util.decoded(authorization);
	try {
		let params = {};
		params.curAuditUserName = data.userName;
		params.$or = [{
			applyState: 1
		}, {
			applyState: 2
		}]
		const total = await Leave.countDocuments(params)
		ctx.body = util.success(total)
	} catch (err) {
		ctx.body = util.fail(`查询异常：${err.message}`)
	}
})


// 审批列表查询
router.get('/list', async (ctx) => {
	try {
		const {
			applyState
		} = ctx.request.query;
		let authorization = ctx.request.headers.authorization;
		let {
			data
		} = util.decoded(authorization);
		const {
			page,
			skipIndex
		} = util.pager(ctx.request.query)
		const params = {
			"applyUser.userId": data.userId
		}
		if (applyState) params.applyState = applyState;
		// 根据条件查询所有列表
		const query = Leave.find(params)
		const list = await query.skip(skipIndex).limit(page.pageSize)
		const total = await Leave.countDocuments(params);
		ctx.body = util.success({
			page: {
				...page,
				total
			},
			list
		})
	} catch (error) {
		ctx.body = util.fail(`查询异常:${error.stack}`)
	}
})


// 审批编辑、删除、新增功能
router.post('/operate', async (ctx) => {
	const {
		_id,
		action,
		...params
	} = ctx.request.body;
	let res, info;
	try {
		if (action == 'add') {
			let authorization = ctx.request.headers.authorization;
			let {
				data
			} = util.decoded(authorization);
			// 生成申请单号
			let orderNo = "XJ";
			orderNo += util.formateDate(new Date(), "yyyy-MM-dd");
			const total = Leave.countDocuments();
			params.orderNo = orderNo + total;

			// 获取用户当前部门ID
			let id = data.deptId.pop();
			// 查找负责人信息
			let dept = await Dept.findById(id)
			// 获取人事部门和财务部门负责人信息
			let userList = await Dept.find({
				deptName: {
					$in: ['人事部门', '财务部门']
				}
			})
			let auditUsers = dept.userName;
			let auditFlows = [{
				userId: dept.userId,
				userName: dept.userName,
				userEmail: dept.userEmail
			}]
			userList.map(v => {
				auditFlows.push({
					userId: v.userId,
					userName: v.userName,
					userEmail: v.userEmail
				})
				auditUsers += ',' + v.userName
			})
			// 赋值参数
			params.auditUsers = auditUsers;
			params.curAuditUserName = dept.userName;
			params.auditLogs = [];
			params.applyUser = {
				userId: data.userId,
				userName: data.userName,
				userEmail: data.userEmail,
			}

			// 数据库创建
			res = await Leave.create(params)
			info = '创建成功'
		} else {
			res = await Leave.findByIdAndUpdate(_id, {
				applyState: 5
			})
			info = '操作成功'
		}
		ctx.body = util.success('', info);
	} catch (error) {
		ctx.body = util.fail(error.stack);
	}

})

// 审批
router.post('/approve', async (ctx) => {
	const {
		action,
		remark,
		_id,
	} = ctx.request.body;
	let authorization = ctx.request.headers.authorization;
	let {
		data
	} = util.decoded(authorization);
	let params = {};
	try {
		// 1、待审批 2、审批中 3、审批拒绝 4、审批通过 5、作废
		let doc = await Leave.findById(_id)
		let auditLogs = doc.auditLogs || [];
		if (action == 'refuse') {
			params.applyState = 3;
		} else {
			// 审核通过
			if (doc.auditFlows.length == doc.auditLogs.length) {
				ctx.body = util.success('当前申请单已处理，请勿重复提交！')
				return
			} else if (doc.auditFlows.length == doc.auditLogs.length + 1) {
				params.applyState = 4;
			} else if (doc.auditFlows.length > doc.auditLogs.length) {
				params.applyState = 2;
				params.curAuditUserName = doc.auditFlows[doc.auditLogs.length + 1, userName];
			}
		}
		auditLogs.push({
			userId: data.userId,
			userName: data.userName,
			createTime: new Date(),
			remark,
			action: action == 'refuse' ? '审批拒绝' : '审批通过'
		})
		params.auditLogs = auditLogs;
		let res = await Leave.findByIdAndUpdate(_id, params)

		info = '处理成功'
		ctx.body = util.success('', info);
	} catch (error) {
		ctx.body = util.fail(error.stack);
	}


})

module.exports = router;